<template>
  <div ref="box" class="layout">
    <!--    创建bom树形结构-->
    <div ref="treeRef" class="tree-container">
      <div class="btn-layout" style="background: #ecf5ff">
        <el-dropdown trigger="click" :hide-on-click="true" class="btnleft">
          <el-button size="mini" type="primary">
            {{ $t('market.treehandle') }}<!--节点操作-->
            <i class="el-icon-arrow-down el-icon--right" />
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="addTree">
              {{ $t('market.treeAdd') }}<!--添加节点-->
            </el-dropdown-item>
            <el-dropdown-item @click.native="empty">
              {{ $t('market.treeEmpty') }}<!--清空节点-->
            </el-dropdown-item>
            <el-dropdown-item @click.native="delTree">
              {{ $t('market.treeDel') }}<!--删除节点-->
            </el-dropdown-item>
            <el-dropdown-item @click.native="setNode">
              {{ $t('market.treeSet') }}<!--标记节点-->
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown trigger="click" :hide-on-click="true" class="btnleft">
          <el-button size="mini" type="primary">
            {{ $t('btn.save') }}<!--保存-->
            <i class="el-icon-arrow-down el-icon--right" />
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="temporary">
              {{ $t('btn.save') }}<!--保存-->
            </el-dropdown-item>
            <el-dropdown-item @click.native="treeSubmit">
              {{ $t('btn.sub') }} <!--提交-->
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown trigger="click" :hide-on-click="true" class="btnleft">
          <el-button size="mini" type="primary">
            {{ $t('btn.audit') }}<!--审核-->
            <i class="el-icon-arrow-down el-icon--right" />
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="treeAdopt">
              {{ $t('btn.audit') }}<!--审核通过-->
            </el-dropdown-item>
            <el-dropdown-item @click.native="treeDeAudit">
              {{ $t('btn.noAudit') }}<!--反审核-->
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown trigger="click" :hide-on-click="true" class="btnleft">
          <el-button size="mini" type="primary">
            {{ $t('btn.config') }}<!--业务操作-->
            <i class="el-icon-arrow-down el-icon--right" />
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="copyBom">
              {{ $t('market.copyBom') }}<!--复制BOM-->
            </el-dropdown-item>
            <el-dropdown-item @click.native="newMateriel">
              {{ $t('menu.createMateriel') }}<!--新增物料-->
            </el-dropdown-item>
            <el-dropdown-item @click.native="updatePrice">
              {{ $t('market.upPrice') }}<!--更新价格-->
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <!--            研发才能看到-->
        <el-dropdown
          v-if="button('bom:confirmYf')"
          trigger="click"
          :hide-on-click="true"
          class="btnleft"
        >
          <el-button size="mini" type="primary">
            {{ $t('market.yfConfig') }}<!--研发操作-->
            <i class="el-icon-arrow-down el-icon--right" />
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="research">
              {{ $t('market.research') }}<!--研发确认-->
            </el-dropdown-item>
            <el-dropdown-item @click.native="identification">
              {{ $t('market.identification') }}<!--新产品标识-->
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <!--            IE 才能看到-->
        <el-dropdown
          v-if="button('bom:confirmIe')"
          trigger="click"
          :hide-on-click="true"
          class="btnleft"
        >
          <el-button size="mini" type="primary">
            {{ $t('market.IEconfig') }}<!--IE操作-->
            <i class="el-icon-arrow-down el-icon--right" />
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="ieConfirm">
              {{ $t('market.ieConfirm') }}<!--IE确认-->
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div style="overflow: hidden;height: 83vh">
        <span v-show="bomState" class="bom-state">{{ $t('market.copyState') }}<!--复制bom状态--></span>
        <el-input v-model.trim="filterText" placeholder="输入关键字进行过滤" size="mini" style="max-width: 400px;margin: 0 5px;" />
        <div class="treeBom">
          <el-tree
            ref="tree"
            :data="data"
            node-key="id"
            :default-expand-all="false"
            :expand-on-click-node="false"
            :default-expanded-keys="defauExpended"
            highlight-current
            class="tree"
            :indent="0"
            :filter-node-method="filterNode"
            @node-click="selectNode"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <div class="title-tree">
                <span :class="{ 'red-node': Boolean(data.isSymbol) }">
                  {{ data.label }}
                </span>
                <i
                  v-show="data.isEdit !== 0"
                  :class="data.icon"
                  @click.stop="handleMateriel(data, node)"
                />
                <el-input
                  v-model="data.consumption"
                  class="consumption"
                  :placeholder="$t('market.dosage')"
                  :disabled="data.isEdit === 0"
                >
                  <i
                    v-show="false"
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click.stop="getConsumption(node, data)"
                  />
                </el-input>
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="data.fdescripTion"
                  placement="top-start"
                >
                  <div class="descripTion">{{ data.fdescripTion }}</div>
                </el-tooltip>
              </div>
            </span>
          </el-tree>
        </div>
      </div>
    </div>
    <div ref="resize" class="resize" @mousedown="handleResize" />
    <div ref="mid" class="operation">
      <div v-show="bomType === 1" class="newly-build">
        <!--        新增bom-->
        <div v-show="isAbleAdd === 0 || isAbleAdd === 1" @click.stop="aotuTab = false">
          <el-tabs v-model="activeName" type="border-card">
            <el-tab-pane :label="$t('market.bomInfo')" name="addBom">
              <div class="tool">
                <el-button style="margin-right: 10px;" size="mini" @click="getRefreshNode(data[0].label)">{{ $t('btn.reload') }}<!--刷新--></el-button>
                <el-dropdown trigger="click">
                  <el-button type="primary" size="mini">
                    {{ $t('btn.save') }}<!--保存-->
                    <i class="el-icon-arrow-down el-icon--right" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="handleSubmit">
                      {{ $t('btn.save') }}<!--保存-->
                    </el-dropdown-item>
                    <el-dropdown-item @click.native="bomSubmit">
                      {{ $t('btn.sub') }}<!--提交-->
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-dropdown trigger="click" style="margin-left: 10px;">
                  <el-button type="warning" size="mini">
                    {{ $t('btn.audit') }}<!--审核-->
                    <i class="el-icon-arrow-down el-icon--right" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="bomAdopt">
                      {{ $t('btn.audit') }}<!--审核-->
                    </el-dropdown-item>
                    <el-dropdown-item @click.native="bomDeAudit">
                      {{ $t('btn.noAudit') }}<!--反审核-->
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-button
                  size="mini"
                  type="primary"
                  style="margin-left: 10px;"
                  @click="handleCopyBom"
                >
                  {{ $t('market.copyBom') }}<!--复制bom-->
                </el-button>
                <el-button size="mini" type="warning" @click="handleReverse">
                  {{ $t('market.reverseBom') }}<!--反查bom-->
                </el-button>
                <div class="summation">
                  {{ $t('market.materialcost') }}:<!--物料成本-->
                  <span class="color-text">
                    {{
                      Math.round((materialScience + Number.EPSILON) * 100) /
                        100
                    }}元
                  </span>
                  {{ $t('market.documentstatus') }}:<!--审核状态-->
                  <el-tag :type="auditColor" size="mini">
                    {{ auditStatus }}
                  </el-tag>
                </div>
              </div>
              <div class="form-layout">
                <el-upload
                  class="avatar-uploader"
                  disabled
                  action="#"
                  :show-file-list="false"
                >
                  <el-image
                    v-if="prodValue.FIMG"
                    :src="prodValue.FIMG"
                    class="avatar"
                    :preview-src-list="[prodValue.FIMG]"
                  />
                </el-upload>
                <jc-form
                  :option-value="prodValue"
                  :options="prodOptions"
                  @handleMagnifier="handleMagnifier"
                >
                  <!-- bug警告：建议别添加输入框宽度，否则icon无法点击 -->
                  <el-input
                    v-model="prodValue.FNUMBER"
                    size="mini"
                    style="position: relative"
                    :disabled="isDisabled"
                  >
                    <i
                      slot="prefix"
                      class="iconfont icon-jin-rud-ao-bo"
                      @click="handleDetailMater"
                    />
                    <i
                      slot="suffix"
                      class="el-input__icon el-icon-search"
                      style="position: absolute;right: 0;"
                      @click="handleMateriel"
                    />
                  </el-input>
                </jc-form>
              </div>
              <div style="margin-bottom: 5px;">
                <el-button
                  size="mini"
                  style="margin-bottom: -5px;"
                  @click="newHang"
                >
                  {{ $t('btn.newHang') }}<!--新增行-->
                </el-button>
                <el-button
                  size="mini"
                  style="margin-bottom: 5px;"
                  @click="delHang"
                >
                  {{ $t('btn.delHang') }}<!--删除行-->
                </el-button>
              </div>
              <jc-table
                :table-data="sonTableData"
                serial
                get-row-keys="FMATERIALID"
                :table-header="sonTableHeader"
                class="materiel-table"
                :table-height="tableHeight"
                @rowClick="rowClick"
              >
                <el-table-column
                  :label="$t('market.materImg')"
                  prop="FIMG"
                  align="center"
                  width="80px"
                >
                  <template slot-scope="scope">
                    <el-image
                      :src="$img + scope.row.FIMG"
                      class="materielImg"
                      :preview-src-list="bomSrcList"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  :label="$t('market.fmodel')"
                  prop="FMODEL"
                  align="center"
                  min-width="100px"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  :label="$t('market.fmaterial')"
                  prop="FNUMBER"
                  align="center"
                  width="160px"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model.trim="scope.row.FNUMBER"
                      size="mini"
                      :disabled="isDisabled"
                      @input="getAtuo(scope.$index, scope.row.FNUMBER)"
                    >
                      <i
                        slot="prefix"
                        class="iconfont icon-jin-rud-ao-bo"
                        @click="handleSonMateriel(scope.row.FNUMBER)"
                      />
                      <i
                        slot="suffix"
                        class="el-input__icon el-icon-search"
                        @click="handleAddBom(scope.$index)"
                      />
                    </el-input>
                    <div
                      v-if="aotuTab && tableIndex === scope.$index"
                      :class="tableIndex < 7 ? 'tabPosit' : 'tabPosit1'"
                    >
                      <number-code
                        :bom-code="bomCode"
                        :fnumber="fnumber1"
                        @material="sonSelectRow"
                      />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  :label="$t('shop.fname2')"
                  prop="fname"
                  align="center"
                  min-width="130px"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  :label="$t('market.fdescripTion')"
                  prop="FDESCRIPTION"
                  align="center"
                  min-width="130px"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  :label="$t('shop.fspecificaTion')"
                  prop="FSPECIFICATION"
                  align="center"
                  min-width="100px"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  :label="$t('market.dosage')"
                  prop="FDOSAGE"
                  align="center"
                  width="80px"
                >
                  <template slot-scope="scope">
                    <el-input-number
                      v-model="scope.row.FDOSAGE"
                      :disabled="isDisabled"
                      :precision="4"
                      :step="0.0001"
                      :min="0.0"
                      size="mini"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  :label="$t('market.funit')"
                  prop="FUNITNAME"
                  align="center"
                  width="60px"
                />
                <el-table-column
                  :label="$t('market.fprice')"
                  prop="FPRICE"
                  align="center"
                  width="80px"
                >
                  <template slot-scope="scope">
                    <el-input-number
                      v-model="scope.row.FPRICE"
                      :disabled="isDisabled"
                      :precision="4"
                      :step="0.0001"
                      :min="0.0"
                      size="mini"
                    />
                  </template>
                </el-table-column>
                <el-table-column :label="$t('market.issueType')" align="center">
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.FISSUETYPE"
                      size="mini"
                      disabled
                      @input="value => handleIssuing(scope.$index, value)"
                    >
                      <el-option
                        v-for="item in issueMaterialsOptions"
                        :key="item.FVALUE"
                        :label="item.FISSUETYPE"
                        :value="item.FVALUE"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  :label="$t('market.isskip')"
                  prop="FISSKIP"
                  align="center"
                  width="60px"
                >
                  <template slot-scope="scope">
                    <el-checkbox v-model="scope.row.FISSKIP" :disabled="isDisabled" />
                  </template>
                </el-table-column>
              </jc-table>
            </el-tab-pane>
            <el-tab-pane :label="$t('market.other')" name="other">
              <jc-form :option-value="otherUrlObject" :options="otherOptions" />
              <jc-table
                :table-header="logTableHeader"
                :table-data="otherLogTableData"
                serial
                table-height="65.96vh"
              />
              <jc-pagination
                v-show="otherPagination.total > 0"
                :total="otherPagination.total"
                :page.sync="otherPagination.pageNum"
                :limit.sync="otherPagination.pageSize"
                @pagination="handleOther"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
        <jc-copy-bom
          v-show="isCopyBom"
          :f-n-u-m-b-e-r="FNUMBER"
          @replaceNode="handleReplaceNode"
          @jumpDetail="handleJumpDetail"
        />
      </div>
      <div v-show="bomType === 2">
        <!--        复制物料-->
        <jc-copy-materiel
          v-show="switchCopy"
          :fnumber="fnumber"
          @addMateriel="handleCopyMateriel"
        />
        <!--        详情物料-->
        <jc-detail-materiel
          v-show="switchDetail"
          :fnumber="fnumber"
          @showMateriel="handleShowMateriel"
        />
        <!--        新增物料-->
        <jc-new-materiel
          v-show="switchNew"
          :is-new-materiel="isNewMateriel"
          @newMateriel="handleNewMateriel"
        />
      </div>
      <div v-show="bomType === 3">
        <h2>{{ $t('market.leftDate') }}<!--请点击左侧数据--></h2>
      </div>
    </div>
    <!--    父项列表弹窗-->
    <el-dialog
      v-dialogDrag
      class="dialogClass"
      :title="$t('menu.materielList')"
      model
      top="5vh"
      :visible.sync="openDialog"
      :close-on-click-modal="false"
      width="80%"
      destroy-on-close
      @close="closeFun"
    >
      <el-slider v-model="scrollValue" @change="enlargeImg" />
      <div class="dialogForm">
        <!--        父关键词查询-->
        <div v-if="isTable === 0" class="bom-form">
          <search
            ref="inputValue"
            :options="selectData"
            :msg="tacitly"
            @seek="collect"
            @hand="getParentMateriel"
          />
          <el-button
            type="primary"
            size="mini"
            class="search-dialog"
            @click="getParentMateriel"
          >
            {{ $t('btn.search') }}
          </el-button>
        </div>
        <!--        子关键词查询-->
        <div v-else class="bom-form">
          <search
            ref="sonInputValue"
            :options="selectData"
            :msg="tacitly"
            @seek="collect"
            @hand="querySonSearch"
          />
          <el-button
            type="primary"
            size="mini"
            class="search-dialog btn"
            @click="querySonSearch"
          >
            {{ $t('btn.search') }}
          </el-button>
        </div>
      </div>
      <!--      父表区域-->
      <div v-if="isTable === 0">
        <jc-table
          serial
          :table-data="parentTableData"
          table-height="62.8vh"
          :table-header="parentTableHeader"
          @clickRow="parentSelectRow"
        >
          <el-table-column
            :label="$t('market.materImg')"
            prop="FIMG"
            align="center"
            min-width="60px"
          >
            <template slot-scope="scope">
              <el-image
                :src="$img + scope.row.FIMG"
                :preview-src-list="parentSrcList"
                class="materielImg"
              />
            </template>
          </el-table-column>
        </jc-table>
        <jc-pagination
          :total="parentPagination.total"
          :page.sync="parentPagination.pageNum"
          :limit.sync="parentPagination.size"
          @pagination="getParentMateriel"
        />
      </div>
      <!--        子表区域-->
      <div v-else>
        <jc-table
          serial
          :table-data="sonDialogTableData"
          table-height="62.8vh"
          :table-header="sonDialogHeaderTable"
          @clickRow="sonSelectRow"
        >
          <el-table-column
            :label="$t('market.materImg')"
            prop="fimg"
            align="center"
            min-width="60px"
          >
            <template slot-scope="scope">
              <el-image
                :src="$img + scope.row.fimg"
                class="materielImg"
                :preview-src-list="childSrcList"
              />
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('market.fmodel')"
            prop="fmodel"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column :label="$t('market.fmaterial')" align="center" width="150px">
            <template slot-scope="scope">
              {{ scope.row.fnumber }}
            </template>
          </el-table-column>
          <!--审核状态-->
          <template v-slot:btnState="col">
            <el-tag
              :type="col.scope.row.stateColor"
            >
              {{ col.scope.row.fdocumentStatus }}
            </el-tag>
          </template>
          <!--禁用状态-->
          <template v-slot:tagSlot="clo">
            <el-tag v-if="clo.scope.row.fforbidStatus === '否'">
              {{ clo.scope.row.fforbidStatus }}
            </el-tag>
            <el-tag v-else type="danger">
              {{ clo.scope.row.fforbidStatus }}
            </el-tag>
          </template>
        </jc-table>
        <jc-pagination
          :total="sonPagination.total"
          :page.sync="sonPagination.pageNum"
          :limit.sync="sonPagination.size"
          @pagination="getSonTableData"
        />
      </div>
    </el-dialog>
    <jc-reverse ref="mychild" :mat-id="matId" />
    <craft v-if="craftVis" @client="craftData" />
  </div>
</template>

<script>
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import jcDetailMateriel from '@/views/basic/material/detailMateriel'
import jcForm from '@/components/Form'
import jcCopyMateriel from '@/views/basic/createMateriel2'
import jcNewMateriel from '@/views/basic/createMateriel2'
import jcCopyBom from '../copyBom'
import jcReverse from '../treeBom/reverse'
import { uuid } from 'vue-uuid'
import { upDateBom } from '@/api/engineering/editBom'
import {
  queryViewItem,
  queryBomTreeDataList,
  queryMaterialSon,
  insertOrUpdateTempBomTree,
  updateConfirmBomTree,
  updateTempSave,
  updateBomAndChildPrice,
  updateBomTreeReview,
  calculateFdosage,
  updateBomConfirm1,
  updateBomIsNew,
  updateBomConfirm2
} from '@/api/engineering/createBom'
import { queryTBdMaterialList } from '@/api/basicManagement/materielList'
import { queryLog, queryBomTreeDetail } from '@/api/engineering/deitalBom'
import { Disable, toDocument, toMxAmina } from '@/components/ToMxamineState'

export default {
  name: 'TreeBom',
  components: {
    search,
    jcDetailMateriel,
    jcForm,
    jcCopyMateriel,
    jcCopyBom,
    jcNewMateriel,
    jcReverse,
    craft: () => import('@/views/engineering/treeBom/craft'),
    numberCode: () => import('@/components/NumberCode')
  },
  mixins: [searData],
  data() {
    return {
      filterText: '',
      aotuTab: false,
      fnumber1: '',
      bomCode: '1',
      isNewMateriel: true, // 新建物料
      craftVis: false, // 工艺列表
      ftype: 0,
      fbillNo: 'fnumber', // 编码
      data: [
        {
          label: '请添加数据', // 名称
          icon: 'el-icon-search',
          children: []
        }
      ],
      bomType: 3, // 1为BOM， 2为物料， 3为未选中
      isEdit: 1, // 0为不可修改， 1为可修改， 2为复制bom
      isAbleAdd: 0, // 0.不可添加节点(审核通过/审核中) 1.可添加节点(创建/暂存/重新审核)
      isCopyBom: false, // 复制BOM
      treeData: {}, // 选中的节点
      node: '', // 选中node节点
      isTable: 0, // 0为父物料, 1为子物料
      openDialog: false, // 物料弹窗
      // 父项数据
      parentTableData: [],
      matId: 0, // 传给反查Bom的物料id
      // 父项表头
      parentTableHeader: [
        // 搜索编码，物料ID隐藏
        { label: this.$t('market.fmodel'), prop: 'FMODEL' },
        { label: this.$t('market.fmaterial'), prop: 'FNUMBER' },
        { label: this.$t('shop.fname2'), prop: 'fname' },
        { label: this.$t('shop.fspecificaTion'), prop: 'FSPECIFICATION' },
        {
          label: this.$t('market.descrip'),
          prop: 'FDESCRIPTION',
          minWidth: '150px'
        },
        { label: this.$t('market.fprice'), prop: 'FPRICE' },
        { label: this.$t('market.createDate'), prop: 'FCREATEDATE' }
      ],
      // 父分页
      parentPagination: {
        total: 0, // 总条目
        pageNum: 1, // 当前页
        size: 50 // 每页显示多少条数据
      },
      routeData: {},
      materialId: '', // 物料id
      bomId: 0, // 更新成功的bomId
      fmaterialid: '', // 提交物料id
      FNUMBER: '', // 传给详情bom的物料编码
      fnumber: '', // 传给详情物料的物料编码
      /* 右边新增bom    */
      activeName: 'addBom', // 默认在bom
      prodValue: {}, // bom表单值
      prodOptions: {}, // bom表单元素
      // 点击行的下标
      tableIndex: 0,
      serial: 1, // 序列号
      // bom子表数据
      sonTableData: [
        {
          FSEQ: 0, // 序号
          FNUMBER: '', // 物料编码
          FMATERIALID: '', // 物料id
          FDESCRIPTION: '', // 描述
          FSPECIFICATION: '', // 物料规格
          FMATERIALTYPE: '1', // 子项类型
          FISSKIP: false, // 是否跳层
          FISSUETYPE: '1', // 发料方式
          FUNITNAME: '', // 单位
          FPRICE: 0, // 单价
          FDOSAGE: 0, // 用量
          money: 0 // 金额
        }
      ],
      // bom子表头数据
      sonTableHeader: [],
      // 发料方式
      issueMaterialsOptions: [],
      // 子项类型
      materialTypes: [],
      tableHeight: '60vh',
      // 子项弹窗表格数据
      sonDialogTableData: [],
      // 子项弹窗表格表头
      sonDialogHeaderTable: [
        {
          label: this.$t('shop.fname2'),
          prop: 'fname'
        },
        {
          label: this.$t('shop.fspecificaTion'),
          prop: 'fspecificaTion'
        },
        {
          label: this.$t('market.fdescripTion'),
          prop: 'fdescripTion',
          minWidth: '200px'
        },

        { label: this.$t('market.funit'), prop: 'funit', width: '80' },
        {
          label: this.$t('market.createDate'),
          prop: 'fcreateDate'
        },
        {
          label: this.$t('market.forbidStatu'),
          type: 'tag',
          prop: 'fforbidStatus'
        },
        {
          label: this.$t('market.documentstatus'),
          type: 'state',
          prop: 'fdocumentStatus'
        }
      ],
      // 子分页
      sonPagination: {
        total: 0, // 总条目
        pageNum: 1, // 当前页
        size: 50 // 每页显示多少条数据
      },
      defauExpended: [1],
      bomObj: {},
      switchNew: false, // 新增物料
      switchCopy: false, // 复制物料
      switchDetail: true, // 详情物料
      copyStatus: false, // Bom状态0为没点击，1为点击
      materielObj: {}, // 复制物料数据
      newMaterielObj: {}, // 新增物料数据
      bomState: false, // 复制bom提示
      searchValue: '', // 搜索的值
      scrollValue: 60, // 滚动条值
      auditStatus: '', // 审核状态
      auditColor: '', // 审核状态颜色
      width: 60,
      height: 60,
      otherUrlObject: {}, // 其它审核人
      otherLogTableData: [], // 日志数据
      // 日志分页
      otherPagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      isDisabled: false,
      otherOptions: {}, // 其它
      // 其它表头
      logTableHeader: [
        { label: this.$t('market.operator'), prop: 'fname' },
        { label: this.$t('market.pattern'), prop: 'fattributes' },
        { label: this.$t('market.fdate'), prop: 'createDate' },
        { label: this.$t('market.deaprt'), prop: 'fdeaprt' },
        { label: this.$t('market.fmaterial'), prop: 'fbillNo' },
        { label: this.$t('market.ipSite'), prop: 'fip' },
        { label: this.$t('market.describe'), prop: 'fdescribe' }
      ],
      bomSrcList: [], // BOM预览图片
      parentSrcList: [], // 父弹窗图片预览
      childSrcList: [] // 图片预览
    }
  },
  computed: {
    Summation() {
      const num = this.sonTableData.map(item => {
        const { FPRICE, FDOSAGE } = item
        item.money = FPRICE * FDOSAGE
        return item.money
      })
      const total = num.reduce((total, num) => {
        return total + num
      }, 0)
      return parseInt(total * 100) / 100
    },
    materialScience() {
      return this.Summation + Number(this.prodValue.FLABORCOST)
    }
  },
  watch: {
    // 过滤
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    Summation: {
      handler(val) {
        if (val === 0) {
          return
        }
        this.prodValue.FMATERIALCOST = val
      },
      immediate: true,
      deep: true
    },
    materielObj(val) {
      this.routeData = val
      // 让新增物料数据清空
      this.newMaterielObj = {}
      if (JSON.stringify(this.routeData) === '{}') {
        return
      }
      if (this.routeData.id === this.materialId) {
        return
      }
      this.routeData.FNUMBER = this.routeData.fnumber
      this.materialId = this.routeData.id
      this.parentSelectRow(this.routeData)
    }
  },

  created() {
    this.getIssuing()
    this.getSubType()
    this.getSonTableData()
    this.intoBom()
    this.getBomForm()
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 400px)' : '60vh'
  },
  updated() {
    this.setBillNo()
  },
  methods: {
    /* bom审核通过 */
    async bomAdopt() {
      const { code, message } = await updateBomTreeReview({ fid: this.bomId })
      if (code !== 0) {
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      this.getRefreshNode(this.data[0].label)
      this.$message({ showClose: true, message, type: 'success' })
    },
    /* bom反审核 */
    async bomDeAudit() {
      const { code, message } = await updateTempSave({
        matId: this.matId
      })
      if (code !== 0) {
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      this.getRefreshNode(this.data[0].label)
      this.$message({ showClose: true, message, type: 'success' })
    },
    /* bom提交 */
    async bomSubmit() {
      const { code, message } = await updateConfirmBomTree({
        FMATERIALID: this.matId
      })
      if (code !== 0) {
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      this.getRefreshNode(this.data[0].label)
      this.$message({ showClose: true, message, type: 'success' })
    },
    // 输入物料编码
    getAtuo(index, fnumber) {
      this.tableIndex = index
      this.aotuTab = true
      var vm = this
      clearTimeout(vm.timer) // 清除未执行的代码，重置回初始化状态
      vm.timer = setTimeout(() => {
        this.fnumber1 = fnumber
      }, 600)
    },
    confirmation(api) {
      if (!this.bomId) {
        this.$message.warning('请添加根节点bom数据')
        return
      }
      const data = {
        bomId: this.bomId
      }
      api(data).then(res => {
        const { code, message } = res
        if (code !== 0) {
          this.$confirm(message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.$message({ showClose: true, message: message, type: 'success' })
      })
    },
    // 研发确认
    research() {
      this.confirmation(updateBomConfirm1)
    },
    // 标识确认
    identification() {
      this.confirmation(updateBomIsNew)
    },
    // IE 确认
    ieConfirm() {
      this.confirmation(updateBomConfirm2)
    },
    // 放大图片
    enlargeImg(item) {
      this.width = item
      this.height = item
    },
    // 设置红点
    setNode() {
      this.treeData.isSymbol = !this.treeData.isSymbol
    },
    // 反查bom
    handleReverse() {
      this.$refs.mychild.getBomFatherList()
    },
    // 记录搜索操作
    setBillNo() {
      const fbillNo = window.localStorage.getItem('fbillNo')
      if (fbillNo) {
        this.fbillNo = fbillNo
      }
    },
    // 父表格搜索
    handleParent(val) {
      this.$refs.inputValue.searData[0].val = ''
      this.searchValue = val
      this.searCollData.fnumber = this.searchValue
      this.getParentMateriel()
    },
    handleSub(val) {
      this.handleParent(val)
    },
    // 子表格搜索
    handleParent1(val) {
      this.$refs.sonInputValue.searData[0].val = ''
      this.searchValue = val
      this.searCollData.fnumber = this.searchValue
      this.getSonTableData()
    },
    handleSub1(val) {
      this.handleParent1(val)
    },
    // 进入bom渲染数据
    intoBom() {
      const { FNUMBER } = this.$route.params
      if (FNUMBER) {
        this.getIntoBom(FNUMBER)
      }
    },
    // 获取用量
    async getConsumption(node, data) {
      const childFnumber = node.label
      const fatherFnumber = node.parent.label
      const { data: res } = await calculateFdosage({
        childFnumber,
        fatherFnumber
      })
      data.consumption = res
    },
    // 进入bom
    async getIntoBom(fnumber) {
      const { data: res } = await queryBomTreeDetail({ fnumber })
      const { allChildList, matBaseData, bomBaseData, bomType } = res
      if (bomType === 1 && allChildList !== null) {
        this.data = allChildList
        this.FID = bomBaseData.FID
        this.fmaterialid = bomBaseData.FMATERIALID
        const item = toDocument(bomBaseData)
        this.auditStatus = item.FDOCUMENTSTATUS
        this.auditColor = item.stateColor
        this.isDisabled = this.auditStatus === this.$t('market.state1') || this.auditStatus === this.$t('market.state2')
        this.getBomForm()
        // 获取日志记录
        const {
          fcreator, // 创建人
          fcreatedate, // 创建时间
          fmodifier, // 修改人
          fmodifydate, // 修改时间
          fapprover, // 审核人
          fapprovedate, // 审核时间
          fforbidder, // 禁用人
          fforbiddate // 禁用时间
        } = bomBaseData
        this.otherUrlObject = {
          fcreator,
          fcreatedate,
          fmodifier,
          fmodifydate,
          fapprover,
          fapprovedate,
          fforbidder,
          fforbiddate
        }
        this.handleOther(fnumber)
      } else if (bomType === 2 && matBaseData !== null) {
        const { fnumber, fname, fmaterialId } = matBaseData
        this.bomType = bomType
        this.fnumber = fnumber
        this.data.forEach(item => {
          item.fmaterialId = fmaterialId
          item.fnumber = fnumber
          item.label = fnumber
          item.fdescripTion = fname
        })
      }
    },
    // 替换节点复制bom
    handleReplaceNode(val) {
      this.parentSelectRow(val)
    },
    // 新增物料
    newMateriel() {
      this.bomType = 2
      this.switchDetail = false
      this.switchCopy = false
      this.switchNew = true
    },
    // 复制子传过来的数据
    handleCopyMateriel(val) {
      this.materielObj = val
    },
    // 复制创建物料数据
    handleNewMateriel(val) {
      this.newMaterielObj = val
      this.fnumber = val.fnumber
      this.switchDetail = true
      this.switchCopy = false
      this.switchNew = false
    },
    // 展示新增物料
    handleShowMateriel(val) {
      this.fnumber = val
      this.switchDetail = false
      this.switchCopy = true
    },
    // 鼠标按下
    handleResize(e) {
      // resize小横条，
      const { resize, box, treeRef: left, mid } = this.$refs
      resize.style.background = '#818181'
      const startX = e.clientX // 当前小横条位置偏移量
      resize.width = resize.offsetLeft // 树导航的宽度
      document.onmousemove = function(event) {
        // 将文档绑定鼠标移动事件
        const endX = event.clientX // 获取客户端的X轴偏移量
        let moveLen = resize.width + (endX - startX) // 用客户端X轴偏移量减去小横条当前位置得出当前位置
        const maxT = box.clientWidth - resize.offsetWidth // 内容区域宽度减去小控件的宽度得出拉伸的最小宽度
        if (moveLen < 32) {
          // 左边内容最小宽度32px
          moveLen = 32
        }
        // 当前位置 - 与内容宽度 - 150
        if (moveLen > maxT - 150) {
          moveLen = maxT - 150 // 最多拉伸右边内容区域不得小于150px
        }
        left.style.width = `${moveLen}px` // 树形数据内容区当前宽度
        mid.style.width = box.clientWidth - moveLen - 10 + 'px' // 主体内容区当前宽度
        document.onmouseup = function() {
          resize.style.background = '#d6d6d6'
          document.onmousemove = null // 事件移除
          document.onmouseup = null // 事件移除
        }
      }
    },
    // 更新价格
    async updatePrice() {
      if (!this.fmaterialid) {
        this.$message.warning('请先暂存再更新价格！')
        return
      }
      const { fmaterialId, label } = this.data[0]
      const matId = fmaterialId
      const { code, message } = await updateBomAndChildPrice({
        matId
      })
      if (code !== 0) {
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      this.$message({ showClose: true, message: message, type: 'success' })
      this.getRefreshNode(label)
    },
    // 保存bom
    async handleSubmit() {
      const fTreeEntity = this.sonTableData.map(item => {
        const {
          FUNITNAME,
          FISSUETYPE,
          FMATERIALID,
          FISSKIP,
          FMATERIALTYPE,
          FDOSAGE,
          FPRICE
        } = item
        return {
          FUNITNAME,
          FISSUETYPE,
          FISSKIP: Number(FISSKIP),
          FMATERIALID,
          FMATERIALTYPE,
          FDOSAGE,
          FPRICE
        }
      })
      const { fmaterialId, bomId } = this.treeData
      if (!fmaterialId) {
        this.$message.warning('请点击左边需保存的树节点，再点保存')
        return
      }
      const DATA = {
        flg: false,
        FLABORCOST: this.prodValue.FLABORCOST,
        FMATERIALID: fmaterialId,
        fcraftId: this.prodValue.fcraftId,
        FID: bomId,
        fTreeEntity
      }
      // if (DATA.FLABORCOST === 0) {
      //   this.$message.warning('人工成本不能小于0,请重新输入!')
      //   return
      // }
      for (const item of DATA.fTreeEntity) {
        const ARRAY = Object.values(item)
        const RES = ARRAY.includes('' || undefined) || DATA.FMATERIALID === 0
        if (RES === true || RES.FDOSAGE === 0) {
          this.$message.warning('表格数据不能为空或用量不能为0!')
          return
        }
      }
      const { code, message } = await upDateBom(DATA)
      if (code === 0) {
        this.$message({ showClose: true, message: message, type: 'success' })
        this.getRefreshNode(this.data[0].label)
      } else if (code === 1) {
        this.$message.error(message)
      } else if (code === 2) {
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            DATA.flg = true
            const { message, code } = await upDateBom(DATA)
            if (code === 0) {
              this.$message({
                showClose: true,
                message: message,
                type: 'success'
              })
              this.getRefreshNode(this.data[0].label)
            } else if (code === 1) {
              this.$confirm(message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
            }
          })
          .catch(() => {
            this.$message.info('已取消保存')
          })
      }
    },
    // 提交
    async treeSubmit() {
      // 必须暂存成功才调用提交接口
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const temporaryCode = await this.temporary()
      if (temporaryCode !== 0) {
        loading.close()
      }
      if (temporaryCode === 0) {
        const { code, message } = await updateConfirmBomTree({
          FMATERIALID: this.fmaterialid
        })
        if (code !== 0) {
          loading.close()
          this.$confirm(message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.$message({ showClose: true, message, type: 'success' })
        this.getRefreshNode(this.data[0].label)
        loading.close()
      }
    },
    // 暂存
    async temporary() {
      // 如果是空节点，则清空节点
      const checkRecursion = data => {
        data.forEach(item => {
          const arr = []
          const index = item.children.findIndex(res => {
            if (res.children.length !== 0) {
              arr.push(res)
            }
            return res.fnumber === ''
          })
          if (index !== -1) {
            item.children.splice(index, 1)
          } else {
            if (arr.length !== 0) {
              checkRecursion(arr)
            }
          }
        })
      }
      checkRecursion(this.data)

      this.bomState = false
      this.data.forEach(item => {
        this.bomObj = item
      })
      // 递归遍历出需要的数据
      const recursion = data => {
        const obj = {}
        // 如果是物料节点
        if (data.bomData == null || JSON.stringify(data.bomData) === '{}') {
          data.bomData = {}
          data.childTable = []
          data.bomData.FMATERIALID = data.fmaterialId
          this.$set(data.bomData, 'FLABORCOST', 0)
        }
        // 如果是bom节点
        obj.consumption = data.consumption // 用量
        obj.isSymbol = data.isSymbol // 红色节点
        obj.flaborCost = data.bomData.FLABORCOST // 人工成本
        obj.fmaterialId = data.bomData.FMATERIALID // 物料id
        obj.childTable = data.childTable.map(item => {
          const { FISSKIP } = item
          item.FISSKIP = Number(FISSKIP)
          return item
        }) // 表格数据
        obj.childList = [] // 节点数据
        data.children.forEach(item => {
          item.isSymbol = Number(item.isSymbol)
          const obj2 = recursion(item)
          obj2 ? obj.childList.push(obj2) : []
        })
        return obj
      }
      const bomData = recursion(this.bomObj)
      const res = {
        fuserId: window.sessionStorage.getItem('fuserId'),
        bomData
      }
      const { data, code, message } = await insertOrUpdateTempBomTree(res)
      if (code !== 0) {
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      const { fmaterialid } = data
      this.fmaterialid = fmaterialid
      this.$message({ showClose: true, message, type: 'success' })
      this.treeData = {}
      this.getRefreshNode(this.data[0].label)
      return code
    },
    // 反审核
    async treeDeAudit() {
      const { code, message } = await updateTempSave({
        matId: this.fmaterialid
      })
      if (code !== 0) {
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      this.$message({ showClose: true, message, type: 'success' })
      this.getRefreshNode(this.data[0].label)
    },
    // 发料数据
    async getIssuing() {
      const { data: res } = await queryViewItem({
        viewName: 'SX_V_UNIT_ISSUETYPE'
      })
      this.issueMaterialsOptions = res.list.map(item => {
        return { FISSUETYPE: item.fname, FVALUE: item.fid }
      })
    },
    // 子项数据
    async getSubType() {
      const { data: res } = await queryViewItem({
        viewName: 'SX_V_BOMCHILDTYPE'
      })
      this.materialTypes = res.list.map(item => {
        return { FMATERIALTYPE: item.fname, FVALUE: item.fid }
      })
    },
    // 发料方式
    handleIssuing(index, value) {
      const materials = this.sonTableData[index]
      this.$set(materials, 'FISSUETYPE', value)
    },
    // 子项类型
    handleSubType(index, value) {
      const subItem = this.sonTableData[index]
      this.$set(subItem, 'FMATERIALTYPE', value)
    },
    // 复制bom
    copyBom() {
      this.$confirm('此操作将产生一个新的bom，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$message({
            type: 'success',
            message: '复制bom成功!'
          })
          this.bomState = true
          this.data[0].label = ''
          const copyRecursion = data => {
            data.forEach(item => {
              item.isEdit = 1
              copyRecursion(item.children)
            })
          }
          this.copyStatus = true
          copyRecursion(this.data)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 拿物料传过来的数据赋值物料节点
    async selectNode(data, node) {
      const {
        isEdit,
        bomData,
        label,
        bomId,
        bomType,
        childTable,
        fmaterialId,
        isAbleAdd
      } = data
      // 左边tree树展开节点
      this.defauExpended[1] = data.id
      this.saveReload = label
      this.isAbleAdd = isAbleAdd
      this.isEdit = isEdit
      const treeData = this.treeData
      // 如果是bom
      if (bomType === 1) {
        this.bomType = 1
        const item = toDocument(bomData)
        this.auditStatus = item.FDOCUMENTSTATUS
        this.auditColor = item.stateColor
        this.isDisabled = this.auditStatus === this.$t('market.state1') || this.auditStatus === this.$t('market.state2')
        this.getBomForm()
        // 复制bom关闭
        this.isCopyBom = false
        this.FNUMBER = label
        this.prodValue = bomData
        this.bomId = bomId
        this.matId = fmaterialId
        this.handleOther(label)
        this.bomSrcList = childTable.map(item => item.FIMG)
        this.sonTableData = childTable.map(item => {
          const { FISSKIP } = item
          const value = Number(FISSKIP)
          item.FISSKIP = Boolean(value)
          return item
        })
        // 如果是物料
      } else {
        this.bomType = 2
        this.fnumber = label
        this.matId = fmaterialId
        this.switchCopy = false
        this.switchDetail = true
        this.switchNew = false
      }
      this.treeData = data
      this.node = node
      this.routeData = this.newMaterielObj
      if (!this.routeData || JSON.stringify(this.routeData) === '{}') {
        return
      }
      const { fmaterialId: id, fnumber, fdescripTion } = this.routeData
      if (id === this.materialId) {
        return
      } else if (isEdit === 0) {
        this.$message.warning('无法将物料数据，添加到无法修改的节点上')
      }
      this.materialId = id
      treeData.bomType = 2
      treeData.fmaterialId = id
      treeData.fnumber = fnumber
      treeData.fdescripTion = fdescripTion
      treeData.label = fnumber
    },
    // 子类搜索
    querySonSearch() {
      this.sonPagination.pageNum = 1
      this.getSonTableData()
    },
    // 新增行
    newHang() {
      this.sonTableData.push({
        FMATERIALID: this.serial++, // 唯一的id
        FSEQ: this.serial++, // 序号
        FNUMBER: null, // 物料编码
        FDESCRIPTION: null, // 物料描述
        FISSKIP: false, // 是否跳层
        FSPECIFICATION: null, // 物料规格
        FUNITNAME: '', // 单位
        FMATERIALTYPE: '1', // 选中值
        FISSUETYPE: 42, // 选中值
        FPRICE: 0, // 单价
        FDOSAGE: 0, // 用量
        money: 0 // 金额
      })
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 删除行
    delHang() {
      this.sonTableData.splice(this.indexSelf, 1)
    },
    // 新增子bom
    async handleAddBom(index) {
      this.isTable = 1
      this.tableIndex = index
      this.openDialog = true
      this.getSonTableData()
    },
    // 获取子bom数据
    async getSonTableData() {
      const { pageNum, size } = this.sonPagination
      const postData = {
        pageNum,
        fdocumentStatus: 'c',
        pageSize: size,
        search: this.searCollData
      }
      const { data: res, code, message } = await queryTBdMaterialList(postData)
      if (code !== 0) {
        this.$message.warning(message)
        return
      }
      const { array, total } = res
      this.sonDialogTableData = array.map(res => {
        return (toMxAmina(res), Disable(res))
      })
      this.childSrcList = array.map(item => item.fimg)
      this.sonPagination.total = total
    },
    // 双击子bom
    async sonSelectRow(item) {
      const data = {
        fmateriAalId: item.fmaterialId,
        fnumber: item.fnumber
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const { data: res, code, message } = await queryMaterialSon(data)
      if (code !== 0) {
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      loading.close()
      const {
        fname,
        FUNITNAME,
        FDOSAGE,
        FMATERIALID,
        FNUMBER,
        FPRICE,
        FDESCRIPTION,
        FISSKIP,
        FSPECIFICATION,
        FISSUETYPEID
      } = res
      const obj = {
        fname,
        FUNITNAME,
        FDOSAGE,
        FMATERIALID,
        FNUMBER,
        FPRICE,
        FDESCRIPTION,
        FISSKIP,
        FSPECIFICATION,
        FISSUETYPEID
      }
      for (const key in obj) {
        this.sonTableData[this.tableIndex][key] = obj[key]
      }
      this.openDialog = false
    },
    // 刷新树节点数据
    async getRefreshNode(fnumber) {
      const { data: res } = await queryBomTreeDetail({ fnumber })
      const { allChildList, bomBaseData, childTableData } = res
      this.data = allChildList
      // 刷新bom信息数据
      const treeData = this.treeData
      treeData.bomData = bomBaseData
      treeData.childTable = childTableData
      // 这两句是第一时间赋值，而不是双击了还是没有数据还需要再点击一下
      this.prodValue = bomBaseData
      let bom_data
      /**
       * @description: 递归获取对应层的状态
       * @param {Array} array 树的数组
       * @return {*}
       * @author: JackLi
       */
      const auditStatus = (array) => {
        for (let i = 0; i < array.length; i++) {
          const { bomId, bomData, children } = array[i]
          if (this.bomId === bomId) {
            bom_data = bomData
            break
          }
          auditStatus(children)
        }
      }
      auditStatus(allChildList)
      const item = toDocument(bom_data)
      this.auditStatus = item.FDOCUMENTSTATUS
      this.isDisabled = this.auditStatus === this.$t('market.state1') || this.auditStatus === this.$t('market.state2')
      this.auditColor = item.stateColor
      this.getBomForm()
      // 刷新日志记录
      const {
        fcreator, // 创建人
        fcreatedate, // 创建时间
        fmodifier, // 修改人
        fmodifydate, // 修改时间
        fapprover, // 审核人
        fapprovedate, // 审核时间
        fforbidder, // 禁用人
        fforbiddate // 禁用时间
      } = bomBaseData
      this.otherUrlObject = {
        fcreator,
        fcreatedate,
        fmodifier,
        fmodifydate,
        fapprover,
        fapprovedate,
        fforbidder,
        fforbiddate
      }
      this.handleOther(fnumber)
    },
    // 添加节点
    addTree() {
      const treeData = this.treeData
      if (this.isAbleAdd === 0) {
        this.$message.warning(
          '该节点无法创建物料，请检查当前节点或父节点是否审核通过或审核中'
        )
        return
      }
      const bomData = {
        id: uuid.v1(),
        fmaterialId: uuid.v1(),
        label: '请添加数据',
        bomData: {},
        fnumber: '', // 物料编码
        isSymbol: 0, // 默认不是红色节点
        consumption: null, // 用量为0
        icon: 'el-icon-search',
        bomType: 1,
        isEdit: 1,
        childTable: [],
        flaborCost: 0,
        fdescripTion: '',
        children: []
      }
      if (!treeData.children) {
        this.$set(treeData, 'children', [])
      }
      treeData.children.push(bomData)
    },
    // 审核通过
    async treeAdopt() {
      if (JSON.stringify(this.data[0].bomData) === '{}') {
        this.$message.warning('请添加数据')
        return
      }
      const { FID: fid } = this.data[0].bomData
      const { code, message } = await updateBomTreeReview({ fid })
      if (code !== 0) {
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      this.$message({ showClose: true, message, type: 'success' })
      this.getRefreshNode(this.data[0].label)
    },
    // 删除节点
    delTree() {
      if (!this.node) {
        return
      }
      const parent = this.node.parent
      if (!parent) {
        this.$message.warning('请点击节点再删除！')
        return
      }
      const children = parent.data.children || parent.data
      const index = children.findIndex(
        d => d.fmaterialId === this.treeData.fmaterialId
      )
      if (this.node.id === 1 || this.node.level === 1) {
        this.$message.warning('不能删除首条数据')
        return
      }
      if (this.isEdit === 0) {
        this.$message.warning(
          '无法删除节点，请检查当前节点或父节点是否审核通过或审核中'
        )
        return
      }
      children.splice(index, 1)
    },
    // 分页
    async getParentMateriel() {
      const { pageNum, size: pageSize } = this.parentPagination
      const DATA = {
        pageNum,
        pageSize,
        isOld: 1,
        fnumberGroup: this.searCollData.fnumber,
        search: this.searCollData
      }
      const { data: RES, total } = await queryBomTreeDataList(DATA)
      this.parentTableData = RES.map(res => {
        return toMxAmina(res)
      })
      this.parentSrcList = RES.map(item => item.FIMG)
      this.parentPagination.total = total
    },
    // 打开父物料编码
    handleMateriel(data, node) {
      if (data instanceof Array) {
        data = this.treeData
      }
      this.openDialog = true
      this.treeData = data
      this.node = node
      this.isTable = 0
      this.getParentMateriel()
    },
    // 双击父物料弹窗
    async parentSelectRow(item) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const { data: res, code } = await queryBomTreeDetail({
        fnumber: item.FNUMBER
      })
      if (code !== 0) {
        this.$message.warning('获取数据失败！')
        loading.close()
        return
      }
      loading.close()
      // 判断当前节点和返回的物料编码是否一致
      if (this.copyStatus) {
        const arr = []
        const editParentLabel = node => {
          const label = node.label
          if (!label) {
            return
          }
          arr.push(label)
          editParentLabel(node.parent)
        }
        editParentLabel(this.node.parent)
        // 颠倒数组，并去重数组
        const arrData = [...new Set(arr)].reverse()
        const emptyLabel = data => {
          data.forEach(item => {
            const result = arrData.indexOf(item.label)
            if (result !== -1 || !item.label) {
              item.label = ''
              emptyLabel(item.children)
            } else {
              return item
            }
          })
        }
        emptyLabel(this.data)
      }
      const treeData = this.treeData
      if (res.bomType === 1) {
        const { bomBaseData, childTableData, allChildList } = res
        this.FNUMBER = bomBaseData.FNUMBER
        const item = toDocument(bomBaseData)
        this.auditStatus = item.FDOCUMENTSTATUS
        this.isDisabled = this.auditStatus === this.$t('market.state1') || this.auditStatus === this.$t('market.state2')
        this.getBomForm()
        this.auditColor = item.stateColor
        // 获取其它页签需要的id，调用页签接口数据
        this.FID = bomBaseData.FID
        treeData.bomData = bomBaseData
        treeData.childTable = childTableData
        // 这两句是第一时间赋值，而不是双击了还是没有数据还需要再点击一下
        this.prodValue = bomBaseData

        /** 赋值其它数据 */
        const {
          fcreator, // 创建人
          fcreatedate, // 创建时间
          fmodifier, // 修改人
          fmodifydate, // 修改时间
          fapprover, // 审核人
          fapprovedate, // 审核时间
          fforbidder, // 禁用人
          fforbiddate // 禁用时间
        } = bomBaseData
        this.otherUrlObject = {
          fcreator,
          fcreatedate,
          fmodifier,
          fmodifydate,
          fapprover,
          fapprovedate,
          fforbidder,
          fforbiddate
        }
        this.handleOther(this.FNUMBER)
        this.sonTableData = childTableData.map(item => {
          const { FISSKIP } = item
          const value = Number(FISSKIP)
          item.FISSKIP = Boolean(value)
          return item
        })
        // 清空children的数据
        treeData.children = []
        const handleAllChildList = () => {
          allChildList.forEach(item => {
            const {
              isSymbol,
              bomType,
              bomId,
              children,
              fdescripTion,
              icon,
              label,
              isEdit,
              childTable,
              fmaterialId,
              isAbleAdd
            } = item
            this.isAbleAdd = isAbleAdd
            this.bomType = 1
            this.FNUMBER = label
            this.bomId = bomId
            treeData.isAbleAdd = isAbleAdd
            treeData.isSymbol = isSymbol
            treeData.fmaterialId = fmaterialId
            treeData.bomId = bomId
            treeData.isEdit = isEdit
            treeData.label = label
            treeData.bomType = bomType
            treeData.fnumber = label
            treeData.children = children
            treeData.icon = icon
            treeData.fdescripTion = fdescripTion
            treeData.childTable = childTable
          })
        }
        if (!this.treeData.children) {
          this.$message.warning('没有children数组')
          return
        }
        if (this.treeData.children.length !== 0) {
          // 如果children有值,则清空再赋值
          this.treeData.children = []
          handleAllChildList()
        } else {
          // 否则直接赋值
          handleAllChildList()
        }
      } else {
        treeData.children = []
        // 如果是物料
        treeData.bomData = {}
        treeData.childTable = []
        const { bomType } = res
        const { fnumber, fdescripTion, fmaterialId } = res.matBaseData
        this.bomType = bomType
        this.fnumber = fnumber
        treeData.fmaterialId = fmaterialId
        treeData.fnumber = fnumber
        treeData.label = fnumber
        treeData.bomType = bomType
        treeData.fdescripTion = fdescripTion
        this.treeData = {}
      }
      this.openDialog = false
    },
    // 删除节点bom
    deleteBom(index) {
      if (index === 0) {
        this.$confirm('删除此bom将无法新增子bom, 是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.sonTableData.splice(index, 1)
            this.$message.success('删除bom成功')
          })
          .catch(() => {
            this.$message.info('已取消删除')
          })
        return
      }
      this.sonTableData.splice(index, 1)
      this.$message.success('删除bom成功')
    },
    // 清空
    empty(ev) {
      this.$confirm(
        ev === 1
          ? '该操作会清空所有的节点，请确保保存数据后再进行此操作。'
          : '确定清空所有节点嘛?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.bomType = 3
          this.data = [
            {
              id: 1,
              bomData: {}, // 右边form数据
              fmaterialId: 0, // 物料id
              label: '请添加数据', // 名称
              fnumber: '', // 物料编码
              bomType: 2,
              consumption: null, // 用量为0
              isSymbol: 0, // 默认不是红色节点
              icon: 'el-icon-search',
              isEdit: 1, // 0为不可修改， 1为可修改
              childTable: [],
              fdescripTion: '', // 描述
              flaborCost: 0, // 人工成本
              children: []
            }
          ]
        })
        .catch(() => {
          this.$message.info('已取消清空')
        })
    },
    // 关闭弹窗页数回第一页
    closeFun() {
      this.searchValue = ''
      this.parentPagination.pageNum = 1
      this.sonPagination.pageNum = 1
      Object.keys(this.searCollData).forEach(key => {
        this.searCollData[key] = ''
      })
    },
    // 物料详情
    detailMateriel() {
      this.bomType = 2
      this.switchCopy = false
      this.switchDetail = true
    },
    // 跳转物料详情
    handleJumpDetail(val) {
      this.fnumber = val
      this.detailMateriel()
    },
    // 父物料详情
    handleDetailMater() {
      this.fnumber = this.prodValue.FNUMBER
      this.detailMateriel()
    },
    // 子物料详情
    handleSonMateriel(fnumber) {
      this.fnumber = fnumber
      this.detailMateriel()
    },
    // 跳转copyBom
    handleSwitchCopyBom(val) {
      this.isCopyBom = val
      this.isAbleAdd = null
    },
    // 隐藏显示日志, 获取表单数据
    async handleOther(fnumber) {
      const fbillNo = this.FNUMBER || fnumber
      const { data: res, code, message } = await queryLog({
        ...this.otherPagination,
        fbillNo: `BOM:${fbillNo}`
      })
      if (code !== 0) {
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      const { array, total } = res
      this.otherLogTableData = array
      this.otherPagination.total = total
    },
    /* 复制bom */
    handleCopyBom() {
      this.isCopyBom = true
      this.isAbleAdd = null
    },
    // 打开工艺列表
    handleMagnifier(val) {
      if (val === 'fcraftName') {
        this.craftVis = true
      }
    },
    // 获取工艺数据
    craftData(item) {
      if (item.fid) {
        this.prodValue.fcraftName = item.fname
        this.prodValue.fcraftId = item.fid
        this.prodValue.FLABORCOST = item.totalSumPrice
      }
      this.craftVis = false
    },
    // 过滤
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 获取表单控件
    getBomForm() {
      this.otherOptions = {
        fcreator: {
          label: this.$t('market.creator'),
          disabled: 'disabled'
        },
        fcreatedate: {
          label: this.$t('market.createDate'),
          disabled: 'disabled'
        },
        fmodifier: {
          label: this.$t('market.modifier'),
          disabled: 'disabled'
        },
        fmodifydate: {
          label: this.$t('market.modifyDate'),
          disabled: 'disabled'
        },
        fapprover: {
          label: this.$t('market.approver'),
          disabled: 'disabled'
        },
        fapprovedate: {
          label: this.$t('market.approveDate'),
          disabled: 'disabled'
        },
        fforbidder: {
          label: this.$t('market.forbider'),
          disabled: 'disabled'
        },
        fforbiddate: {
          label: this.$t('market.forbidDate'),
          disabled: 'disabled'
        }
      }
      this.prodOptions = {
        FNUMBER: {
          type: 'slot',
          label: this.$t('market.fmaterial'),
          span: 6,
          disabled: this.isDisabled,
          labelWidth: '120px'
        },
        FMODEL: {
          label: this.$t('market.fmodel'),
          span: 18,
          disabled: true,
          labelWidth: '120px'
        },
        fname: {
          label: this.$t('shop.fname2'),
          labelWidth: '120px',
          disabled: true
        },
        FDESCRIPTION: {
          label: this.$t('market.fdescripTion'),
          labelWidth: '120px',
          type: 'input_textarea',
          span: 16,
          disabled: true
        },
        FMATERIALCOST: {
          label: this.$t('market.matercost'),
          labelWidth: '120px',
          disabled: true
        },
        FSPECIFICATION: {
          label: this.$t('shop.fspecificaTion'),
          labelWidth: '120px',
          disabled: true
        },
        FUNIT: {
          label: this.$t('market.materunit'),
          labelWidth: '120px',
          disabled: true
        },
        FWEIGHTUNIT: {
          label: this.$t('market.weightUnit'),
          labelWidth: '120px',
          disabled: true
        },
        FLABORCOST: {
          label: this.$t('market.planLabor'),
          type: 'number',
          disabled: this.isDisabled,
          labelWidth: '120px'
        },
        fcraftName: {
          label: this.$t('market.craft'),
          type: 'magnifier',
          disabled: this.isDisabled,
          labelWidth: '120px',
          readonly: 'readonly',
          placeholder: '请输入工艺'
        },
        FGROSSWEIGHT: {
          label: this.$t('market.grossweight'),
          labelWidth: '120px',
          disabled: true
        },
        FNETWEIGHT: {
          label: this.$t('market.netweight'),
          labelWidth: '120px',
          disabled: true
        },
        actualcost: {
          label: this.$t('market.actualcost'),
          type: 'number',
          disabled: true,
          labelWidth: '120px'
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import 'src/styles/tree/index';
.treeBom {
  height: 80vh;
  overflow-y: auto;
  overflow-x: hidden;
}
/* tree树选中颜色 */
.el-tree::v-deep .el-tree-node:focus>.el-tree-node__content {
  background-color: #e0ecff !important;
}
.el-tree::v-deep .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
  background-color: #e0ecff !important;
}
.bom-form {
  position: relative;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;

  .btn {
    transform: translateY(18%);
    margin-left: 450px !important;
  }
}
.tree-container {
  background-color: white;
}
.custom-tree-node {
  display: flex;
  align-items: center;
}
.materielImg {
  width: 2.08vw;
  height: 3.68vh;
}

.avatar {
  width: 150px;
  height: 150px;
}
.custom-tree-node ::v-deep .el-input {
  font-size: 12px;
  width: 80px;
}
.consumption ::v-deep .el-input__inner {
  width: 80px;
  height: 20px;
  padding: 0 35px 0 5px;
}
.consumption ::v-deep .el-input__suffix {
  display: flex;
  align-items: center;
}
.form-layout {
  display: flex;
  align-items: center;
  justify-content: space-around;
  height: 200px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  font-size: 14px;
}

.el-form-item {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 0;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.tabPosit {
  padding: 5px;
  box-shadow: 0 0 2px #aaa;
  position: absolute;
  top: 3.5vh;
  left: 0;
  background-color: rgba(255, 255, 255, 1);
  z-index: 99999 !important;
}
.tabPosit1 {
  padding: 5px;
  box-shadow: 0 0 2px #aaa;
  position: absolute;
  top: -25.69vh;
  left: 0;
  background-color: rgba(255, 255, 255, 1);
  z-index: 9999;
}
</style>
